package com.study.experiment07.action;

import com.opensymphony.xwork2.ActionSupport;
import com.study.experiment07.entity.Person;
import com.study.experiment07.util.HibernateSessionFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

public class PersonAction extends ActionSupport {
    private String username;
    private String password;
    private Integer age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String savePerson() {
        Person person = new Person();

        person.setUsername(username);
        person.setPassword(password);
        person.setAge(age);

        java.sql.Timestamp registerDate = new java.sql.Timestamp(new java.util.Date().getTime());

        person.setRegisterDate(registerDate);

        Session session = HibernateSessionFactory.getSession();
        Transaction ts = session.beginTransaction();
        try {
            session.save(person);
            ts.commit();
        } catch (Exception ex) {
            if (null != ts) {
                ts.rollback();
            }

        } finally {
            session.close();
        }

        return "success";
    }

    public String Query() {
        List list = null;
        Session session = HibernateSessionFactory.getSession();
        try {
            String sql = "select * from person where username=? and password=?";
            Query query = session.createSQLQuery(sql);
            query.setParameter(0, username);
            query.setParameter(1, password);
            list = query.list();
            return list.size() > 0 ? "success" : "error";
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            session.close();
        }
        return "error";
    }
}